﻿using System;
using System.Collections.Generic;
using System.Text;
using SourceCode.Workflow.Client;
using ASBCC.Database.Entity;

namespace ASBCC.Workflow.K2Manager
{
    public static class K2Helper
    {
        public static string GetProcessName(string procName)
        {
            return string.Format("{0}\\{1}", K2Config.K2ProcessFolder, procName);
        }

        public static string GetDestinationName(int userId)
        {
            return string.Format("K2:{0}\\{1}", K2Config.K2DomainName, userId);
        }

        public static string GetAdminDestinationName()
        {
            return string.Format("K2:{0}\\{1}", K2Config.K2DomainName, K2Config.K2AdminName);
        }

        public static string GetAuditUsername(string destination)
        {
            if (string.IsNullOrEmpty(destination)) return string.Empty;
            int pos = destination.LastIndexOf('\\');
            return destination.Substring(pos + 1, destination.Length - pos - 1);
        }

        public static string GetSerialNumber(int procInstID, int actInstDestID)
        {
            return string.Format("{0}_{1}", procInstID, actInstDestID);
        }

        public static void AssignDataFields(DataFields dataFields, SerializableDictionary dataFieldsSource)
        {
            if (dataFieldsSource == null) return;
            foreach (KeyValuePair<string, object> dataField in dataFieldsSource)
            {
                if (ContainsFields(dataFields,dataField.Key))
                {
                    dataFields[dataField.Key].Value = dataField.Value;
                }
            }
        }

        public static bool ContainsFields(DataFields dataFields,string fieldName)
        {
            foreach (DataField field in dataFields)
            {
                if (field.Name == fieldName)
                {
                    return true;
                }
            }
            return false;
        }

        public static SerializableDictionary ConvertDataFieldsToDictionary(DataFields dataFields)
        {
            SerializableDictionary dict = new SerializableDictionary();
            foreach (DataField dataField in dataFields)
            {
                dict.Add(dataField.Name, dataField.Value);
            }
            return dict;
        }

        public static K2AuditDestination ConvertXmlFieldsToAuditDestination(XmlFields xmlFields)
        {
            string value = xmlFields[K2Consts.XmlField_Key_AuditDestination].Value;
            if (string.IsNullOrEmpty(value)) return null;
            return K2AuditDestination.LoadXml(value);
        }

        public static void AssignXmlFields(XmlFields xmlFields, K2AuditDestination k2AuditDestination)
        {
            if (k2AuditDestination == null)
            {
                //当走向最后一个节点时
                xmlFields[K2Consts.XmlField_Key_AuditDestination].Value = string.Empty;
                return;
            }

            for (int i = 0; i < k2AuditDestination.ActivityDestinationList.Count; i++)
            {
                string key;
                if (i == 0)
                {
                    key = K2Consts.XmlField_Key_AuditDestination;
                }
                else
                {
                    key = string.Format(K2Consts.XmlField_Key_AuditDestinationFormat, i);
                }
                xmlFields[key].Value = k2AuditDestination.ActivityDestinationList[i].ExportXmlFieldValue();
            }
        }

        public static SerializableDictionary MergeDictionary(SerializableDictionary oldDict, SerializableDictionary newDict)
        {
            SerializableDictionary dict = new SerializableDictionary();
            foreach (KeyValuePair<string, object> pair in oldDict)
            {
                dict.Add(pair.Key, pair.Value);
            }
            foreach (KeyValuePair<string, object> pair in newDict)
            {
                if (dict.ContainsKey(pair.Key))
                {
                    dict[pair.Key] = pair.Value;
                }
                else
                {
                    dict.Add(pair.Key, pair.Value);
                }
            }
            return dict;
        }

        public static string K2ActionerToOwner(string actioner)
        {
            string[] parts = actioner.Split('\\');
            return parts[parts.Length - 1];
        }

        public static void MergeWorklistItemsAndMyActivitySet(SourceCode.Workflow.Management.WorklistItems worklistItems, MyActivityTableEntitySet myActivitySet, out List<MyActivityTableEntity> myActivityListToBeMoved, out List<SourceCode.Workflow.Management.WorklistItem> newWorkItemListAfterAction)
        {
            myActivityListToBeMoved = new List<MyActivityTableEntity>();
            newWorkItemListAfterAction = new List<SourceCode.Workflow.Management.WorklistItem>();

            if (myActivitySet != null)
            {
                foreach (MyActivityTableEntity myActivity in myActivitySet)
                {
                    if (!MyActivityInWorklistItems(myActivity, worklistItems))
                    {
                        myActivityListToBeMoved.Add(myActivity);
                    }
                }
            }

            if (worklistItems != null)
            {
                foreach (SourceCode.Workflow.Management.WorklistItem worklistItem in worklistItems)
                {
                    if (!WorklistItemInMyActivitySet(worklistItem, myActivitySet))
                    {
                        newWorkItemListAfterAction.Add(worklistItem);
                    }
                }
            }
        }

        public static MyActivityTableEntity CloneMyActivity(MyActivityTableEntity myActivity)
        {
            using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
            {
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
                formatter.Serialize(ms, myActivity);
                ms.Position = 0;
                return formatter.Deserialize(ms) as MyActivityTableEntity;
            }
        }

        public static int GetActualOwnerId(int ownerId, int delegateFromId)
        {
            if (delegateFromId <= 0) return ownerId;
            return delegateFromId;
        }

        public static string SerializeObject(object obj)
        {
            return null;
        }

        public static object DeserializeObject(string text)
        {
            return null;
        }

        public static string SerializeDictionary(Dictionary<string, object> obj)
        {
            if (obj == null || obj.Count == 0) return null;
            return null;
        }

        public static Dictionary<string, object> DeserializeDictionary(string text)
        {
            return null;
        }

        private static bool Equals(MyActivityTableEntity myActivity, SourceCode.Workflow.Management.WorklistItem worklistItem)
        {
            int actInstDestID1 = myActivity.K2ActInstDestID.HasValue ? myActivity.K2ActInstDestID.Value : 0;
            int procInstID1 = myActivity.K2ProcInstID.HasValue ? myActivity.K2ProcInstID.Value : 0;
            string destination1 = myActivity.K2Destination;
            int actInstDestID2 = worklistItem.ActInstDestID;
            int procInstID2 = worklistItem.ProcInstID;
            string destination2 = worklistItem.Destination;

            return actInstDestID1 == actInstDestID2 && procInstID1 == procInstID2 && destination1 == destination2;
        }

        private static bool MyActivityInWorklistItems(MyActivityTableEntity myActivity, SourceCode.Workflow.Management.WorklistItems worklistItems)
        {
            if (worklistItems == null) return false;
            foreach (SourceCode.Workflow.Management.WorklistItem worklistItem in worklistItems)
            {
                if (Equals(myActivity, worklistItem)) return true;
            }
            return false;
        }

        private static bool WorklistItemInMyActivitySet(SourceCode.Workflow.Management.WorklistItem worklistItem, MyActivityTableEntitySet myActivitySet)
        {
            if (myActivitySet == null) return false;
            foreach (MyActivityTableEntity myActivity in myActivitySet)
            {
                if (Equals(myActivity, worklistItem)) return true;
            }
            return false;
        }
    }
}
